#include "game_protocol.h"

#ifdef __cplusplus
extern "C" {
#endif

#include "message/gamemessage.h"
#include <pthread.h>
#include "videodecode.h"
#include "network/networkevents.h"


struct game_protocol {
	pthread_t thread;
	int is_running;

	int is_connected;
	message_received_cb on_receive_cb;
};

struct game_protocol gmprot;
const char* ctrl_names[] = {
		"UP", "DOWN", "LEFT", "RIGHT",
		"UP_LEFT", "UP_RIGHT", "DOWN_LEFT", "DOWN_RIGHT",
		"DOWN_CLAW"
};

void game_message_received_cb(const char* command, const char* data, int code)
{
	if (gmprot.on_receive_cb)
		gmprot.on_receive_cb(command, data, code);
}

void game_message_status_cb(const char* status)
{
	if (strcmp(status, "CONNECTED") == 0) {
		gmprot.is_connected = 1;
	}
	else {
		gmprot.is_connected = 0;
	}

	if (gmprot.on_receive_cb) {
		gmprot.on_receive_cb("CONNECT_ACK", status, gmprot.is_connected);
	}
}

void* game_protocol_thread(void* p)
{
	gmprot.is_running = 1;

	gamemsg_init();
	network_init();

	while (gmprot.is_running) {
		now_time2 = sys_gettime();
		network_process_events();
		gamemsg_process();
		usleep(1000);
	}

	gamemsg_uninit();
	network_uninit();
	gmprot.thread = 0;
	return NULL;
}

void gameproto_init(message_received_cb receive_cb)
{
	memset(&gmprot, 0, sizeof(gmprot));
	gmprot.on_receive_cb = receive_cb;

	// 创建解码线程
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&gmprot.thread, &attr, game_protocol_thread, NULL);
}

void gameproto_uninit()
{
	if (gmprot.thread) {
		int i;
		gmprot.is_running = 0;
		for (i = 0; i < 10; i++) {
			if (!gmprot.thread)
				break;
			usleep(1000 * 50);
		}
	}
}

void gameproto_sendmessage(const char* command, const char* data, int code, const char* version)
{
	if (!gmprot.is_running)
		return;

	if (strcmp(command, "CONNECT") == 0) {
		gamemsg_connect(data, code, version, game_message_received_cb, game_message_status_cb);
	}
	else if (strcmp(command, "QUIT") == 0) {
		if (gmprot.is_connected) {
			gamemsg_send(command, data, 0);
		}
		gamemsg_disconnect(code);
		gmprot.is_connected = 0;
	}
	else if (gmprot.is_connected) {
		gamemsg_send(command, data, code);
	}
}

void gameproto_sendcontrol(int ctrl, const char* param)
{
	if (gmprot.is_connected && ctrl >= CTRL_UP && ctrl <= CTRL_DOWN_CLAW) {
		gamemsg_send("CONTROL_DEVICE", ctrl_names[ctrl], 0);
	}
}

#ifdef __cplusplus
}
#endif


